import pandas as pd
import os

def calculate_fractals(df):
    fractals = []

    for i in range(1, len(df) - 1):
        if df.iloc[i]['high'] > df.iloc[i - 1]['high'] and df.iloc[i]['high'] > df.iloc[i + 1]['high'] and \
           df.iloc[i]['low'] > df.iloc[i - 1]['low'] and df.iloc[i]['low'] > df.iloc[i + 1]['low']:
            df.at[i, 'top_fractal'] = True
        if df.iloc[i]['low'] < df.iloc[i - 1]['low'] and df.iloc[i]['low'] < df.iloc[i + 1]['low'] and \
           df.iloc[i]['high'] < df.iloc[i - 1]['high'] and df.iloc[i]['high'] < df.iloc[i + 1]['high']:
            df.at[i, 'bottom_fractal'] = True

    return df

if __name__ == '__main__':
    try:
        df = pd.read_json('../static/included_bnb_usdt_klines.json')
        print("成功读取 included_bnb_usdt_klines.json 文件")
    except Exception as e:
        print(f"读取 included_bnb_usdt_klines.json 文件失败: {e}")
        raise

    try:
        df['top_fractal'] = False
        df['bottom_fractal'] = False
        df = calculate_fractals(df)
        print("成功计算顶分型和底分型")
    except Exception as e:
        print(f"计算顶分型和底分型失败: {e}")
        raise

    try:
        os.makedirs('../static', exist_ok=True)
        print("确保 static 目录存在")
    except Exception as e:
        print(f"创建 static 目录失败: {e}")
        raise

    try:
        with open('../static/initial_fractals_bnb_usdt_klines.json', 'w') as f:
            df.to_json(f, orient='records', indent=4)
        print("初始分型数据已保存到 static/initial_fractals_bnb_usdt_klines.json")
    except Exception as e:
        print(f"保存初始分型数据失败: {e}")
        raise
